package com.water.camera.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.water.camera.R;
import com.water.camera.view.temp.BaseTemp;

import org.json.JSONArray;
import org.json.JSONObject;

public class TemplateAdapter extends RecyclerView.Adapter {

    JSONArray array;
    BaseTemp template;
    int layoutId;

    public TemplateAdapter(JSONArray a, BaseTemp template, int layoutId) {
        array = a;
        this.template = template;
        this.layoutId = layoutId;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false);
        return new Holder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof Holder) {
            ((Holder) holder).bind(position);
        }
    }

    @Override
    public int getItemCount() {
        return array == null ? 0 : array.length();
    }

    class Holder extends RecyclerView.ViewHolder {
        TextView title, desc;

        Holder(View view) {
            super(view);
            title = view.findViewById(R.id.title);
            desc = view.findViewById(R.id.desc);
        }

        void bind(int p) {
            try {
                JSONObject obj = array.getJSONObject(p);
                title.setText(obj.getString("name"));
                desc.setText(obj.getString("desc"));
            } catch (Throwable e) {
                e.printStackTrace();
            }
            itemView.setOnClickListener(v -> template.toEdit());
        }
    }
}
